import React, { useState, useEffect, useRef } from 'react'
import { Avatar, Modal, Image, DatePicker, message, Space, Tabs } from 'antd';
import { ModalForm, ProFormDateRangePicker, ProFormSelect, ProTable } from '@ant-design/pro-components';
import TheButton from "@/components/TheButton/index.jsx";
import { apiAppCouponInfoPage, apiAppCouponInfoEnd, apiGetStoreInfo, } from "@/api/couponManagement/couponsList.js";
import moment from 'moment';
import Decimal from "decimal.js";
import { useNavigate } from "react-router-dom";
import { useWindowSize } from "@/utils/useWindowSize.js";

const { confirm } = Modal;

export default () => {
  const [loadings, setLoadings] = useState([]);
  const navigate = useNavigate();
  const [activeKey, setActiveKey] = useState("P");
  const actionRef = useRef();
  const {width, height} = useWindowSize();
  const [tbScrollH, setTbScrollH] = useState('40vh');

  const columns = [
    {
      title: "优惠券ID",
      dataIndex: "couponId",
      key: "couponId",
    },
    {
      title: "优惠券名称",
      dataIndex: "couponTitle",
      key: "couponTitle",
      ellipsis: true,
      width: 200
    },
    {
      title: "创建时间",
      dataIndex: "time",
      key: "time",
      hideInTable: true,
      renderFormItem: () => {
        return <ProFormDateRangePicker
          formItemProps={{
            className: 'form-rangePicker-w',
          }}
        />
      },
      search: {
        transform: (value) => {
          return {
            startTime: value ? moment(value[0]).format('YYYY-MM-DD') + ' 00:00:00' : undefined,
            stopTime: value ? moment(value[1]).format('YYYY-MM-DD') + ' 23:59:59' : undefined,
          };
        }
      }
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      valueEnum: {
        "all": { text: '全部' },
        "J": { text: '代金券' },
        'Z': { text: '折扣券' },
      },
      hideInTable: true,
      initialValue: 'all'
    },
    {
      title: "优惠券类型",
      dataIndex: "couponType",
      key: "couponType",
      hideInSearch: true,
      valueEnum: {
        "J": { text: '代金券' },
        'Z': { text: '折扣券' },
      },
    },
    {
      title: "范围",
      dataIndex: "commodityScope",
      key: "commodityScope",
      hideInSearch: true,
      valueEnum: {
        0: { text: '全部商品可用' },
        1: { text: '限制品类可用' },
        2: { text: '商品券' },
      }
    },
    {
      title: "优惠",
      dataIndex: "couponPrice",
      key: "couponPrice",
      hideInSearch: true,
      render: (text, render) => {
        let label = ''
        switch (render.usePrice) {
          case -1:
            label = '无门槛，'
            break;
          default:
            label = "满" + (render.usePrice) / 100 + "可用，"
        }
        switch (render.couponType) {
          case 'J':
            label += "减免" + Decimal(text).div(Decimal(100)).toNumber() + "元"
            break;
          case 'Z':
            label += "打" + text / 10 + "折"
            if (render.couponMaxPrice !== -1) {
              label += '，最大折扣金额' + Decimal(render.couponMaxPrice).div(Decimal(100)).toNumber() + '元'
            }
            break;
          default:
            label = "字段值错误"
        }
        return label
      }
    },
    {
      title: "状态",
      dataIndex: "activeStatus",
      key: "activeStatus",
      hideInSearch: true,
      valueEnum: {
        0: { text: '未开始', status: 'Default' },
        1: { text: '进行中', status: 'Processing' },
        2: { text: '已结束', status: 'Success' },
      }
    },
    {
      title: '最近修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      valueType: 'dateTime',
      editable: false,
      hideInSearch: true,
      width: 250
    },
    {
      title: "操作",
      valueType: 'option',
      fixed: "right",
      render: (text, render, index) => {
        return (
          <Space>
            <TheButton haspermi={['couponManagement:couponsList:view']} type="link" onClick={() => onView(render.couponId)}>查看</TheButton>
            {
              render.activeStatus === 0 && <>
                <TheButton haspermi={['couponManagement:couponsList:edit']} type="link" onClick={() => onEdit(render.couponId)}>修改</TheButton>
                <TheButton haspermi={['couponManagement:couponsList:end']} type="link" onClick={() => overNow(render.couponId, render.timeType, index, 0)} loading={loadings[index]}>提前结束</TheButton>
              </>
            }
            {
              render.activeStatus === 1 && <>
                <TheButton haspermi={['couponManagement:couponsList:edit']} type="link" onClick={() => onEdit(render.couponId)}>修改</TheButton>
                <TheButton haspermi={['couponManagement:couponsList:end']} type="link" onClick={() => overNow(render.couponId, render.timeType, index, 0)} loading={loadings[index]}>提前结束</TheButton>
                <TheButton haspermi={['couponManagement:couponsList:record']} type="link" onClick={() => getRecord(render.couponId)}>领取记录</TheButton>
              </>
            }
            {
              render.activeStatus === 2 && <>
                <TheButton haspermi={['couponManagement:couponsList:record']} type="link" onClick={() => getRecord(render.couponId)}>领取记录</TheButton>
              </>
            }
            <TheButton haspermi={['couponManagement:couponsList:cdkList']} type="link" onClick={() => CDKList(render.couponId)}>CDK列表</TheButton>
          </Space>
        );
      },
    },
  ]
  const [items, setItems]= useState([
    {
      key: 'P',
      label: "线上商城"
    },
    {
      key: 'M',
      label: "门店服务"
    },
  ])

  useEffect(() => {
    if (height >= 1080){
      setTbScrollH('47vh')
    }else if(height < 1080 && height >= 960){
      setTbScrollH('40vh')
    }
    getShopInfo()
  }, [])

  const getShopInfo = async () => {
    let storeInfo = await apiGetStoreInfo();
    if (storeInfo.code === 0 && storeInfo.data) {
      if(storeInfo.data.isProprietary === "N"){
        setItems([{
          key: 'P',
          label: "线上商城"
        },])
      }
    }
  }
  const onTabChange = (key) => {
    setActiveKey(key)
    actionRef.current.reloadAndRest();
  }
  const onAdd = () => {
    navigate('/couponManagement/couponList/coupon', {
      state: {
        mode: "add"
      }
    })
  }
  const onView = (couponId) => {
    navigate('/couponManagement/couponList/coupon', {
      state: {
        mode: "view",
        couponId
      }
    })
  }
  const onEdit = (couponId) => {
    navigate('/couponManagement/couponList/coupon', {
      state: {
        mode: "edit",
        couponId
      }
    })
  }
  const overNow = (couponId, timeType, RowIndex, ButIndex) => {
    setLoadings((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[RowIndex] = true;
      return newLoadings;
    });
    confirm({
      title: "提示",
      type: 'warning',
      content: "提前结束优惠券活动可能导致正在领取的消费者领取失败，是否继续关闭？",
      onOk: async () => {
        await apiAppCouponInfoEnd({ couponId, timeType }).then(res => {
          if (res.code === 0) {
            // getData(pageParams)
            actionRef.current.reloadAndRest()
          }
          setLoadings((prevLoadings) => {
            const newLoadings = [...prevLoadings];
            newLoadings[RowIndex] = false;
            return newLoadings;
          });
        })
      },
      onCancel: () => {
        setLoadings((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[RowIndex] = false;
          return newLoadings;
        });
      }
    });
  }

  const getRecord = (couponId) => {
    navigate('/couponManagement/couponList/receipt', {
      state: {
        couponId
      }
    })
  }

  const CDKList = (couponId) => {
    navigate('/couponManagement/couponList/CDKlist', {
      state: {
        couponId
      }
    })
  }

  return <div>
    <TheButton haspermi={['couponManagement:couponsList:add']} key="add" onClick={() => onAdd()}>新建优惠券</TheButton>
    <Tabs defaultActiveKey={activeKey} items={items} onChange={onTabChange} />
    <ProTable
      actionRef={actionRef}
      scroll={{ x: "max-content", y: tbScrollH }}
      rowKey={'couponId'}
      bordered={true}
      options={false}
      columns={columns}
      pagination={{
        defaultPageSize: 10,
        position: ['bottomCenter'],
        showSizeChanger: false
      }}
      params={{
        couponSpecies: activeKey
      }}
      request={async (params, sort, filter) => {
        // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        // 如果需要转化参数可以在这里进行修改
        if (params.type === 'all') {
          delete params.type
        }
        const res = await apiAppCouponInfoPage({
          pageNo: params.current,
          pageSize: params.pageSize,
          ...params
        });
        return {
          data: res.rows,
          // success 请返回 true，
          // 不然 table 会停止解析数据，即使有数据
          success: res.code === 0,
          // 不传会使用 data 的长度，如果是分页一定要传
          total: res.totalCount,
        };
      }}
      search={{
        optionRender: (searchConfig, formProps, dom) => {
          return dom.reverse()
        },
        collapsed: false,
        collapseRender: false
      }}
    />
  </div>
}
